import React from 'react';
import {Storage} from 'storage';

export default class CountdownButton extends React.Component {
    constructor(props) {
        super();

        this.key = props?.sign || 'react-cooldown-button-key';
        this.storage = Storage(this.key, true);

        this.state = {
            countdown: props?.countdown || 60,
            view: props?.view || '获取验证码'
        };
    }

    componentDidMount() {
        let data = this.storage.get();
        let timeout = data?.countdown - Date.now() || 0;
        let timing = this.props['timing'];
        let countdown = parseInt(timeout / 1000);

        timing?.(countdown);
        this.countdownTiming = timeout;

        if (timeout > 0) {
            this.interval = setInterval(() => {

                if (countdown <= 0) {
                    clearInterval(this.interval);
                    this.countdownTiming = 0;
                    this.storage.remove();
                    timing?.(countdown);
                    return;
                }

                timing?.(--countdown)
            }, 1000);
        } else {
            this.countdownTiming = 0;
            this.storage.remove();
        }

    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            view: nextProps?.view,
            disabled: nextProps?.disabled
        });
    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }

    async onClick() {
        if (this.props?.disabled) {
            return;
        }

        if (this.countdownTiming > 0) {
            return;
        }

        let isSuccess = await this.props?.onClick?.();
        let now = Date.now() + ((this.state?.countdown || 60) * 1000);


        isSuccess = typeof isSuccess === 'boolean' ? isSuccess : true;

        if (isSuccess) {
            this.storage.add({
                countdown: now
            });

            this.componentDidMount();
        }
    }

    render() {
        let className = this.props.className || '';
        let classList = className instanceof Array ? className : className.split(' ');

        classList.push('touch-active');
        if (classList.filter(x => x.indexOf('font-size') >= 0).length <= 0) {
            classList.push('font-size-14');
        }

        return (
            <button className={classList.filter(Boolean).join(' ')}
                    disabled={this.props?.disabled}
                    onClick={() => this.onClick()}>{this.state?.view}</button>
        );
    }
}